/*	Gather class definition.
 *
*/

#include "Gather.h"

void Gather::Enter()
{
	DEBUG_PRINT("Gather(%p) entering.\n", this);
}

void Gather::Execute()
{
	std::list<Base*>* bases = BB->GetBases();
	std::list<BWAPI::Unit*>* scvs;
	std::list<MinPatch*>* minList;
	for(std::list<Base*>::iterator base = bases->begin(); base != bases->end(); base++)
	{
		DEBUG_PRINT("Gather(%p) executing.\n", this);
		scvs = (*base)->GetUnitsByType(BWAPI::UnitTypes::Terran_SCV);
		DEBUG_PRINT("Grabbing worker list scvs(%p) of size %d.\n", scvs, scvs->size());
		//For now just getting reference for first base
		minList = (*base)->GetMinerals();
		DEBUG_PRINT("Grabbing minerals list minList(%p) of size %d.\n", minList, minList->size());
		std::list<MinPatch*>::iterator patchToMine;
		int numOfMiners = INT_MAX;
		for(std::list<BWAPI::Unit*>::iterator it = scvs->begin(); it != scvs->end(); it++)

		{
			if((*it)->isIdle())
			{
				numOfMiners = INT_MAX;
				for(std::list<MinPatch*>::iterator minIt = minList->begin(); minIt != minList->end(); minIt++)
				{
					if((*minIt)->mining < numOfMiners)
					{
						numOfMiners = (*minIt)->mining;
						patchToMine = minIt;
						if((*minIt)->mining == 0)
							break;
					}
				}
				if(numOfMiners != INT_MAX)
				{
					(*patchToMine)->mining++;
					DEBUG_PRINT("Sending scv(%p) to mine mineral(%p) that has %d mining.\n", (*it),(*patchToMine),(*patchToMine)->mining );
					(*it)->gather((*patchToMine)->mineral);
				}
			}
		}
	}
	control->FinishWithSuccess();
}

void Gather::Exit()
{
	DEBUG_PRINT("Exiting Gather behavior.\n");
}

bool Gather::CheckConditions()
{
	return true;
	DEBUG_PRINT("Checking Gather conditions.\n");
	std::list<Base*>* bases = BB->GetBases();
	for(std::list<Base*>::iterator base = bases->begin(); base != bases->end(); base++)
	{
		std::list<BWAPI::Unit*>*	scvs = (*base)->GetUnitsByType(BWAPI::UnitTypes::Terran_SCV);
		for(std::list<BWAPI::Unit*>::iterator it = scvs->begin(); it != scvs->end(); it++)
		{
			if((*it)->isIdle())
			{
				DEBUG_PRINT("Checking Gather conditions.  Found SCV.  Returning true.\n");
				return true;
			}
		}
	}
	DEBUG_PRINT("Checking Gather conditions.  Did not find SCV.  Returning false.\n");
	return false;
}